﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.Accessctl.Interfaces.AccessRecord;
using PARK.Accessctl.Entitys;
using PARK.Accessctl.Entitys.Dto.AccessRecord;
using PARK.System.Interfaces.Permission;
using PARK.Common.Util;

namespace PARK.Accessctl.AccessRecord
{
    /// <summary>
    /// 门禁记录服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Access", Name = "Record", Order = 200)]
    [Route("api/access/[controller]")]
    public class AccessRecordService : IAccessRecordService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<AccessRecordEntity> _accessRecordRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IOrganizeService _organizeService; // 机构表仓储

        /// <summary>
        /// 初始化一个<see cref="AccessRecordService"/>类型的新实例
        /// </summary>
        public AccessRecordService(
            ISqlSugarRepository<AccessRecordEntity> accessRecordRepository,
            IUserManager userManager,
             IOrganizeService organizeService)
        {
            _accessRecordRepository = accessRecordRepository;            
            _db = _accessRecordRepository.Context;
            _userManager = userManager;
            _organizeService = organizeService;
        }

        /// <summary>
        /// 获取门禁记录
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<AccessRecordEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<AccessRecordInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取门禁记录列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] AccessRecordListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "passtime" : input.sidx;
                //选中公司查询全部
                var organizeIds = new List<string>();
                if (!input.organizeId.IsNullOrEmpty())
                    organizeIds = await GetSubOrganizeIds(input.organizeId);
                if (input.departId == "96240625-934F-490B-8AA6-0BC775B18468")
                {
                    input.departId = null;
                }
                //通行日期
                List<string> queryBillDate = input.passtime != null ? input.passtime.Split(',').ToObeject<List<string>>() : null;
                DateTime? startBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.First()) : null;
                DateTime? endBilldate = queryBillDate != null ? Ext.GetDateTime(queryBillDate.Last()) : null;
                var data = await _db.Queryable<AccessRecordEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), p => p.CtlSn.Contains(input.keyword) || p.CardNo.Contains(input.keyword) || p.CatCardNo.Contains(input.keyword) || p.JobNo.Contains(input.keyword) || p.ReallName.Contains(input.keyword) || p.DoorNo.Contains(input.keyword))
                    .WhereIF(!string.IsNullOrEmpty(input.doorid), p => p.DoorNo.Contains(input.doorid))
                    .WhereIF(!string.IsNullOrEmpty(input.inOroutName), p => p.InOroutName.Contains(input.inOroutName))
                    .WhereIF(!string.IsNullOrEmpty(input.inOrout), p => p.InOrout.Equals(input.inOrout))
                    .WhereIF(!string.IsNullOrEmpty(input.passStatus), p => p.PassStatus.Equals(input.passStatus))
                    .WhereIF(!string.IsNullOrEmpty(input.departId), p => p.DepartId.Equals(input.departId))
                    //组织机构
                    .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                    //所在区域
                    .WhereIF(!string.IsNullOrEmpty(input.doorAreaName), p => p.DoorAreaId.Equals(input.doorAreaName))
                    //通行日期
                    .WhereIF(queryBillDate != null, a => a.Passtime >= new DateTime(startBilldate.ToDate().Year, startBilldate.ToDate().Month, startBilldate.ToDate().Day, 0, 0, 0))
                    .WhereIF(queryBillDate != null, a => a.Passtime <= new DateTime(endBilldate.ToDate().Year, endBilldate.ToDate().Month, endBilldate.ToDate().Day, 23, 59, 59))
                    .Select(it => new AccessRecordListOutput
                    {
                        id = it.Id,
                        ctlSn = it.CtlSn,
                        ctlName =it.ctlName,
                        ctlInex = it.CtlInex,
                        cardNo = it.CardNo,
                        catCardNo =it.CatCardNo,
                        passtime = it.Passtime,
                        doorNo = it.DoorNo,
                        doorName = it.DoorName,
                        inOrout = it.InOrout,
                        inOroutName = it.InOroutName,
                        passStatus = it.PassStatus,
                        passStatusName = it.PassStatusName,
                        description = it.Description,
                        jobNo = it.JobNo,
                        reallName = it.ReallName,
                        departId = it.DepartId,
                        departName = it.DepartName,
                        doorAreaName = it.DoorAreaName,
                        ctlposition = it.Ctlposition,
                        sortCode = it.SortCode,
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<AccessRecordListOutput>.SqlSugarPageResult(data);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 下属机构
        /// </summary>
        /// <param name="organizeId">机构ID</param>
        /// <returns></returns>
        [NonAction]
        public async Task<List<string>> GetSubOrganizeIds(string organizeId)
        {
            var data = await _organizeService.GetListAsync();
            data = data.TreeChildNode(organizeId, t => t.Id, t => t.ParentId);
            return data.Select(m => m.Id).ToList();
        }
        
        /// <summary>
        /// 删除门禁记录
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<AccessRecordEntity>().FirstAsync(p => p.Id == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                var isOk = await _db.Deleteable<AccessRecordEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
            {
                throw PARKException.Bah("您的权限无法操作!");
            }
        }
    }
}
